import 'dart:convert';
import 'dart:typed_data';

import 'package:crypto/crypto.dart';
import 'package:flutter/material.dart';
import 'package:flutterproject/mvvm/base/base_controller.dart';
import 'package:flutterproject/page/main/controller/main_controller.dart';
import 'package:flutterproject/page/red_package/data/luck_times_bean.dart';
import 'package:flutterproject/page/red_package/data/pick_bean.dart';
import 'package:flutterproject/page/red_package/widget/deng.dart';
import 'package:flutterproject/util/EncryptUtils.dart';
import 'package:flutterproject/util/address_manager.dart';
import 'package:flutterproject/util/dialog_toast/dialog_util.dart';
import 'package:flutterproject/util/dialog_toast/toast_util.dart';
import 'package:flutterproject/util/extension/extension_util.dart';
import 'package:flutterproject/util/extension/widget_extension.dart';
import 'package:flutterproject/util/http/http_client.dart';
import 'package:flutterproject/util/http/http_exception.dart';
import 'package:flutterproject/widget/image_extended.dart';
import 'package:flutterproject/widget/spinning_wheel/spinning_wheel.dart';
import 'package:flutterproject/widget/text/text_common.dart';
import 'package:get/get.dart';

class RedPackageController extends BaseController {
// 创建 GlobalKey，用于获取子组件引用
  final GlobalKey<SpinningWheelState> childKey = GlobalKey();
  final GlobalKey<DengPageState> childKey2 = GlobalKey();

  int currentIndex = 0;
  HttpClient client = Get.find<HttpClient>();

  final mainController = Get.find<MainController>();

  /// 希望抽中几等奖
  int giftIndex = 0;

  LuckTimesBean? luckTimesBean = LuckTimesBean();

  PickBean? pickBean = PickBean();

  int times = 0;

  @override
  void onReady() {
    // TODO: implement onReady
    super.onReady();
    getTimes();
  }

  /// 获取抽奖次数
  Future getTimes() async {
    if ((mainController.productBean?.products?.isEmpty ?? true) ||
        mainController.productBean?.products![currentIndex].id == null) {
      ToastUtil.showTips("未获取到商品列表");
      return;
    }
    try {
      DialogUtil.showLoading();
      luckTimesBean = await client
          .get<LuckTimesBean>(AddressManager.luckTimes, queryParameters: {
        "productId": mainController.productBean?.products![currentIndex].id,
      });
      times = luckTimesBean?.times ?? 0;
      update();
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  /// 获取抽奖次数
  Future pick() async {
    if ((mainController.productBean?.products?.isEmpty ?? true) ||
        mainController.productBean?.products![currentIndex].id == null) {
      ToastUtil.showTips("未获取到商品列表");
      return;
    }
    try {
      DialogUtil.showLoading();
      pickBean = await client.post<PickBean>(AddressManager.pick, data: {
        "productId": mainController.productBean?.products![currentIndex].id,
      });
      times = pickBean?.times ?? 0;
      update();
      if (pickBean?.result == null) {
        ToastUtil.showTips("未获取到抽奖次数");
        return;
      }
      childKey.currentState!.myStartAnimation(pickBean!.result! - 1);
      childKey2.currentState!.start();
      return true;
    } on HttpException catch (e) {
      ToastUtil.showFailed(e.message);
      return false;
    } finally {
      DialogUtil.dismiss();
    }
  }

  void changeIndex(int index) {
    currentIndex = index;
    update(['tab']);
    getTimes();
  }

  void showGiftDialog() {
    DialogUtil.showCustomDialog(
        Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Container(
              width: 655.width,
              height: 663.height,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/image/ic_red01.png'),
                  fit: BoxFit.fill, // 完全填充
                ),
              ),
              child: Column(
                children: [
                  120.heightBox,
                  TextCommon(
                    "恭喜释放",
                    size: 24.sp,
                    lineHeight: 35.sp,
                    color: Color(0xFFDC2C23),
                    fontWeight: FontWeight.w500,
                  ),
                  19.heightBox,
                  TextCommon(
                    (pickBean?.releasedAmount ?? 0).toStringAsFixed(2),
                    size: 60.sp,
                    lineHeight: 87.sp,
                    color: Color(0xFFDC2C23),
                    fontWeight: FontWeight.bold,
                  ),
                  6.heightBox,
                  TextCommon(
                    pickBean?.awardName ?? "",
                    size: 36.sp,
                    lineHeight: 52.sp,
                    color: Color(0xFFDC2C23),
                  ),
                ],
              ),
            ),
            20.heightBox,
            ImageCommon(
              "/icon/ic_x",
              size: 70.width,
            ).addClickEvent(() => DialogUtil.dismiss()),
          ],
        ),
        alignment: Alignment.center);
  }
}